13. Handling Errors
Handling Errors Try Except Finally
Try Statement
We can use try statements to handle exceptions. There are four clauses you can use (one more in addition to those shown in the video).
try: This is the only mandatory clause in atrystatement. The code in this block is the first thing that Python runs in atrystatement.except: If Python runs into an exception while running thetryblock, it will jump to theexceptblock that handles that exception.else: If Python runs into no exceptions while running thetryblock, it will run the code in this block after running thetryblock.finally: Before Python leaves thistrystatement, it will run the code in thisfinallyblock under any conditions, even if it's ending the program. E.g., if Python ran into an error while running code in theexceptorelseblock, thisfinallyblock will still be executed before stopping the program.
Handling Error Specifying Exceptions
Specifying Exceptions
We can actually specify which error we want to handle in an except block like this:
try:
# some code
except ValueError:
# some code
Now, it catches the ValueError exception, but not other exceptions. If we want this handler to address more than one type of exception, we can include a parenthesized tuple after the except with the exceptions.
try:
# some code
except (ValueError, KeyboardInterrupt):
# some code
Or, if we want to execute different blocks of code depending on the exception, you can have multiple except blocks.
try:
# some code
except ValueError:
# some code
except KeyboardInterrupt:
# some code